import React from 'react';
import { withRouter } from 'react-router-dom'
import { MusicSearch, getSearchMultimatch } from "../../api/top/top";
import './SearchMusic.scss'
import { Spin, Menu, Table, Avatar } from 'antd';
import { RightOutlined } from '@ant-design/icons';
import { Link } from "react-router-dom";
import Recommend from "../../components/Recommend/Recommend";
import emitter from "../../event";
const { SubMenu } = Menu;

class SearchMusic extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            findMusic: {},
            loading: false,
            current: '1',
            matchRes: null, // 最佳匹配
            matchMap: {
                album: "专辑",
                artist: "歌手",
                mv: "MV",
                video: "视频",
            },
        }
    }

    componentDidMount(){
        this.SeachMusic()
        // console.info(this.props.match.params.name)
    }

    componentDidUpdate(prevProps,prevState) {
        if(prevProps.location.pathname !== this.props.location.pathname){
            this.SeachMusic()
        }
        // console.info(this.props.match.params.name)
    }


    SeachMusic = (type,page) => {
        this.setState({
            loading: true
        })
        let name = this.props.match.params.name
        let parmas = {
            keywords: name,
            limit: 100,
            offset: page || 0,
            type: type
        }
        MusicSearch(parmas).then(res => {
            const { code, result } = res;
            if(code == 200){
                this.setState({
                    findMusic: result,
                    loading: false
                })
            }else {

            }
        }).catch(() => {

        });
        let Multimatch = {
            keywords: name,
        }
        getSearchMultimatch(Multimatch).then(res => {
            const { code, result } = res;
            if(code == 200){
                this.setState({
                    matchRes: result,
                })
            }else {

            }
        }).catch(() => {

        })
    }


    callback = (e) => {
        this.setState({
            current: e.key
        })
        this.SeachMusic(e.key)
    }

    fitterSinger = (artists) => {
        let artistlsit = []
        artists.map((item,index) => {
            artistlsit.push(
                <span artistid={item.id} className="artistitem">
                    { item.name }
                </span>
            )
        })
        return <div className="artistlsit">{ artistlsit }</div>
    }


    fitterTime = (value) => {
        var theTime = parseInt(value/1000);// 秒
        var middle= 0;// 分
        var hour= 0;// 小时

        if(theTime > 60) {
            middle= parseInt(theTime/60);
            theTime = parseInt(theTime%60);
            if(middle> 60) {
                hour= parseInt(middle/60);
                middle= parseInt(middle%60);
            }
        }
        let Time = parseInt(theTime).toString().padStart(2, '0')
        let Middle = parseInt(middle).toString().padStart(2, '0')
        let Hour = parseInt(theTime).toString().padStart(2, '0')
        var result = "00:"+Time;
        if(middle > 0) {
            result = Middle+":"+Time;
        }
        if(hour> 0) {
            result = Hour + ":" + Middle+":"+Time;
        }
        return result;
    }

    PlayThisSong(event,record){
        console.log(record);
        emitter.emit('PlayAudio',record.id,record);
    }

    render() {
        const { current, matchRes, matchMap } = this.state;
        const { songCount,songs } = this.state.findMusic;

        const columns = [
            {
                title: '音乐标题',
                dataIndex: 'name',
                key: 'name',
                render: text => <span className="table_name">{text}</span>,
            },
            {
                title: '歌手',
                dataIndex: 'artists',
                key: 'artists',
                render: text => <div>
                    {this.fitterSinger(text)}
                </div>,
            },
            {
                title: '专辑',
                dataIndex: 'album',
                key: 'album',
                render: text => <div albumid={text.id} className="album">{text.name}</div>,
            },
            {
                title: '时长',
                dataIndex: 'duration',
                key: 'duration',
                render: text => <span className="table_dt">{this.fitterTime(text)}</span>,
            },
            {
                title: '热度',
                dataIndex: 'mark',
                key: 'mark',
                render: text => <div className="mark_Box">
                    <div className="mark_Long" style={{width: `${text >= 1000? '100%': `${text/10+'%'}`}`}}></div>
                </div>,
            },
        ];

        const matchResList = [];
        if(matchRes){
            for (let key in matchRes){
                if(key !== 'orders'){
                    matchRes[key].map((r,index) => {
                        matchResList.push(
                            <Link class="match-item" to="/" key={key}>
                                <Avatar src={`${
                                    r.picUrl || r.cover ||r.coverUrl
                                }?param=50y50`} size={50}></Avatar>
                                <div className="name">
                                    {matchMap[key]}:
                                    {r.name || r.title}
                                </div>
                                <RightOutlined />
                            </Link>
                        )
                    })
                }
            }
        }

        const pagination = {
            position: ['bottomCenter'],
            pageSize: 100,
            showSizeChanger: false,
        }


        return(
            <div className="SeachMusic">
                <Spin spinning={this.state.loading}>
                    <div className="AllMusic">
                        找到{ songCount }首单曲
                    </div>
                    <Menu className="MusicMenu" onClick={this.callback} selectedKeys={[current]} mode="horizontal">
                        <Menu.Item key="1" >单曲</Menu.Item>
                        <Menu.Item key="100" >歌手</Menu.Item>
                        <Menu.Item key="10" >专辑</Menu.Item>
                        <Menu.Item key="1014" >视频</Menu.Item>
                        <Menu.Item key="1000" >歌单</Menu.Item>
                        <Menu.Item key="1006" >歌词</Menu.Item>
                        <Menu.Item key="1002" >用户</Menu.Item>
                    </Menu>
                    {matchResList.length > 0 ? <span className="match-title">最佳匹配</span> : ''}
                    <div className="match-box">
                        {matchResList}
                    </div>
                    <Table className="Playlist_table" onRow={record => {
                        return {
                            onClick: event => {}, // 点击行
                            onDoubleClick: (event) => this.PlayThisSong(event,record),
                        };
                    }} columns={columns} dataSource={songs} pagination={pagination} />
                </Spin>

            </div>
        )
    }
}

export default withRouter(SearchMusic)